#include "preHeader.h"
#include "ServerService.h"

IServerService::IServerService(const std::string& name)
: m_name(name)
{
}

IServerService::~IServerService()
{
	INetPacket* pck = NULL;
	while (m_PacketStorage.Dequeue(pck)) {
		delete pck;
	}
}

void IServerService::PushRecvPacket(INetPacket* pck)
{
	OnRecvPacket(pck);
}

void IServerService::OnRecvPacket(INetPacket* pck)
{
	m_PacketStorage.Enqueue(pck);
}

void IServerService::UpdateAllPackets()
{
    uint32 opcode = OPCODE_NONE;
    INetPacket *pck = nullptr;
    TRY_BEGIN {

		while (m_PacketStorage.Dequeue(pck)) {
			opcode = pck->GetOpcode();
			switch (HandleOneRecvPacket(*pck)) {
			case SessionHandleCapture:
				break;
			default:
				SAFE_DELETE(pck);
				break;
			}
		}

	} TRY_END
	CATCH_BEGIN(const IException &e) {
		WLOG("`%s` Handle packet opcode[%u] exception occurred.",
			m_name.c_str(), opcode);
		e.Print();
	} CATCH_END
	CATCH_BEGIN(...) {
		WLOG("`%s` Handle packet opcode[%u] unknown exception occurred.",
			m_name.c_str(), opcode);
	} CATCH_END
}

int IServerService::HandleOneRecvPacket(INetPacket& pck)
{
	auto opcode = pck.GetOpcode();
	auto retCode = HandlePacket(pck);
	switch (retCode) {
	case SessionHandleSuccess:
		break;
	case SessionHandleCapture:
		break;
	case SessionHandleUnhandle:
		WLOG("`%s` SessionHandleUnhandle Opcode[%u].", m_name.c_str(), opcode);
		break;
	case SessionHandleWarning:
		WLOG("`%s` Handle Opcode[%u] Warning!", m_name.c_str(), opcode);
		break;
	case SessionHandleError:
		WLOG("`%s` Handle Opcode[%u] Error!", m_name.c_str(), opcode);
		break;
	case SessionHandleKill:
	default:
		WLOG("`%s` Fatal error occurred when processing opcode[%u].", m_name.c_str(), opcode);
		break;
	}
	return retCode != SessionHandleCapture ? SessionHandleSuccess : SessionHandleCapture;
}
